<?php
namespace app\common\model;
use think\Config;
use think\helper\Time;
use traits\model\SoftDelete;

class User extends Base
{
    use SoftDelete;
    protected $deleteTime = 'delete_time'; // 软删除字段
    protected $autoWriteTimestamp = true;

    /**
     * 校对账户密码
     * @param string $username
     * @param string $password
     * @return int 成功返回uid 禁用0 密码错误-1
     */
    public function checkPassword($username,$password)
    {
        $salt = Config::get('salt');
        $info = $this->getArrayByMap(['username'=>$username],'','',false);
        if(empty($info)){
            return -2;
        }else{
            if(isset($info['status']) && $info['status'] == 2){
                return 0;
            }else{
                if(md5($password.$salt) != $info['password']){
                    return -1;
                }else{
                    session('user_id',$info['id']);
                    session('user_data',$info);
                    return $info['id'];
                }
            }
        }
    }

    public function getUserChargeStat()
    {


        $result = $this->where(['status'=>1])->order('id desc')->paginate(15,false,['query'=>request()->param()])
            ->each(function($item, $key){

                $today = Time::today();
                $yes = Time::yesterday();

                // 前天充值
                $where['create_time'] = ['between',[$yes[0]-86400,$yes[1]-86400]];
                $where['status'] = 1;
                $where['user_id'] = $item['id'];
                $last_yes_charge = model('Order')->where($where)->sum('money');

                // 昨天充值
                $where1['create_time'] = ['between',[$yes[0],$yes[1]]];
                $where1['status'] = 1;
                $where1['user_id'] = $item['id'];
                $yes_charge = model('Order')->where($where1)->sum('money');

                // 今天充值
                $where2['create_time'] = ['between',[$today[0],$today[1]]];
                $where2['status'] = 1;
                $where2['user_id'] = $item['id'];
                $today_charge = model('Order')->where($where2)->sum('money');

                // 总充值
                $where3['status'] = 1;
                $where3['user_id'] = $item['id'];
                $total_charge = model('Order')->where($where3)->sum('money');

                $item['last_yes_charge'] = $last_yes_charge;
                $item['yes_charge'] = $yes_charge;
                $item['today_charge'] = $today_charge;
                $item['total_charge'] = $total_charge;
                return $item;
            });

        return $result;
    }

}